package com.orangelife.mobile.myhouse.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.common.jump.LocationJumper;
import com.common.sp.CommSp2;
import com.common.sp.UserSp;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.CountDownHandler;

import com.curry.orangelife.mobile.R;
import com.datatrack.DataTrack;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.verify.biz.SmsHttpBiz;
import com.common.jump.HouseJumper;

import com.orangelife.mobile.login.biz.LoginBiz;
import com.orangelife.mobile.myhouse.biz.HouseBiz;
import com.orangelife.mobile.myhouse.biz.HouseHttpBiz;
import com.orangelife.mobile.myhouse.entity.HouseBean;
import com.orangelife.mobile.myhouse.entity.IndustryEntity;
import com.orangelife.mobile.myhouse.entity.LocationBean;
import com.orangelife.mobile.myhouse.entity.ResidentBean;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 申请认证界面
 * <p/>
 * Created by 吴格非 on 2015/11/12,Modify By wgf on 160621.
 */
public class HouseCertActivity extends OrangeLifeBaseActivity {


    @Bind(R.id.tvCity)
    TextView tvCity;
    @Bind(R.id.tvComm)
    TextView tvComm;
    @Bind(R.id.tvGetCode)
    TextView tvGetCode;
    @Bind(R.id.etName)
    EditText etName;
    @Bind(R.id.etVerifyCode)
    EditText etVerifyCode;
    @Bind(R.id.tvTel)
    TextView tvTel;
    @Bind(R.id.btnRight)
    Button btnCommit;
    @Bind(R.id.btnLeft)
    Button btnCancel;
    @Bind(R.id.tv3)
    TextView tvIdentity;
    @Bind(R.id.tvVoiceCode)
    TextView tvVoiceCode;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.llTip)
    LinearLayout llTip;

    private String currentType;
    /** 0产权人(户主),1亲属,2租户 */
    private String type = "0";
    public static final String PLEASE_SELECT = "请选择";
    private String identity = HouseBean.ROLE_TYPE_OWNER_CODE;
    private CountDownHandler countDownHandler;
    private boolean isCountDown;
    private PopupWindow pw;
    /** 默认发送短信 */
    private boolean isSendSms = true;
    private String commID = "";

    private String city;
    private String comm;
    /** 是否从web界面跳转来 */
    private boolean mIsFromWeb;
    private Bundle mBundle;

    /**Activit 名称**/
    final  String MODULE_NAME="/IA";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_house_cert);
        ButterKnife.bind(this);
        initTitle();
        initView();
        getIntentInfo();

    }

//    @Override
//    public void onBackPressed() {
//        super.onBackPressed();
//        if (mIsFromWeb) {
//            HouseBiz.jumpBackToWeb(HouseCertActivity.this, true);
//        }
//    }

    /**
     * 数据采集体不要删除
     * @return
     */
    public Map<String,Object> getDataTrack(){
        Map<String,Object> map=new HashMap<>();
        map.put("UI_HOST", DataTrack.APP_NAME);
        map.put("UI_PATH", MODULE_NAME);
        return map;
    }

    private void getIntentInfo() {
        mBundle = getIntent().getExtras();
        if (mBundle != null) {
            mIsFromWeb = "0".equals(mBundle.getString("isFromWeb"));
        }
    }


    /** 控制名字是否可以更改,若在该小区未认证则可以输入名字,反之默认名字;若改变了小区,则也可以重置名字 */
    private void chageNameState() {
        if (UserSp.hasCert()) {
            etName.setText(UserSp.getCertName());
            etName.setEnabled(false);
            llTip.setVisibility(View.VISIBLE);
        } else {
            etName.setText("");
            etName.setEnabled(true);
            llTip.setVisibility(View.GONE);
        }
    }

    private void initView() {
        commID = CommSp2.getCommID();
        city = CommSp2.getCityName();
        comm = CommSp2.getCommName();
        tvCity.setText(city);
        tvComm.setText(comm);
        tvIdentity.setText("我是" + getResources().getString(R.string.owner));
        tvTel.setText(UserSp.getRegPhone());
        btnCancel.setText("取消申请");
        btnCommit.setText("提交认证");
        chageNameState();
    }

    private void initTitle() {
        tvTitle.setText(getString(R.string.identity));
    }

    @OnClick({R.id.ib_title_left, R.id.rlSelectCity, R.id.rlSelectComm, R.id.btnLeft, R.id.btnRight, R.id.ivJumpType, R.id.tv3})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rlSelectCity:
                currentType = SelectHouseLocationActivity.TYPE_CITY;
                LocationJumper.jumpToSelectLocation(HouseCertActivity.this, SelectHouseLocationActivity.TYPE_CITY, null);
                resetSelected();
                break;
            case R.id.rlSelectComm:
                currentType = SelectHouseLocationActivity.TYPE_COMM;
                String city = hasSelectPreValue(SelectHouseLocationActivity.TYPE_COMM);
                if (city == null || city.trim().equals("")) {
                    ToastHelper.getInstance().displayToastWithQuickClose("请先选择城市");
                } else {
                    LocationJumper.jumpToSelectLocation(HouseCertActivity.this, SelectHouseLocationActivity.TYPE_COMM, city);
                    resetSelected();
                }
                break;
            case R.id.btnRight:
                dataTrackClick("btnSubmit",null);
                requestCommitCertInfo();
                break;
            case R.id.btnLeft:
                dataTrackClick("btnCancel",null);
                jumpToHouseList();
                break;
            case R.id.ivJumpType:
            case R.id.tv3:
                showPopWinChooseIdentity();
                break;
        }
    }

    private void jumpToHouseList() {
        if (UserSp.hasCert()) {
            HouseJumper.jumpToList(this);
        } else {
            finish();
        }
    }

    private ResidentBean getResidentInfo() {
        String name = etName.getText().toString();
        String tel = tvTel.getText().toString();
        String code = etVerifyCode.getText().toString();
        ResidentBean rb = new ResidentBean();
        rb.setName(name);
        rb.setPhone(tel);
        rb.setCode(code);
        rb.setCommID(commID);
        if (type.equals("0")) {
            identity = HouseBean.ROLE_TYPE_OWNER_CODE;
        }
        if (type.equals("1")) {
            identity = HouseBean.ROLE_TYPE_FAMILY_CODE;
        }
        if (type.equals("2")) {
            identity = HouseBean.ROLE_TYPE_TENANT_CODE;
        }
        rb.setIdentity(identity);
        return rb;
    }

    /** 提交认证 */
    private void requestCommitCertInfo() {
        ResidentBean rb = getResidentInfo();
        if (!HouseBiz.validateCertInfo(rb)) {
            return;
        }
        showDialog(this);
        final String type = this.type;
        HouseHttpBiz.commitCertInfo(new VolleyHttpUtil.ResponseCallBack() {
                                        @Override
                                        public void handleResponse(JSONObject response, int errCode) {
                                            closeDialog();
                                            etVerifyCode.setText("");
                                            IndustryEntity ib = HouseHttpBiz.handleCommitCertInfo2(response, HouseCertActivity.this, null);
                                            if (ib != null) {
                                                if (!type.equals("0")) {
                                                    jumpToTenantCert2(ib);
                                                } else {
                                                    if (mIsFromWeb) {/*网页认证用!*/
                                                        HouseBiz.jumpBackToWeb(HouseCertActivity.this, true);
                                                    } else {
                                                        jumpToOwnerCertOk(ib);
                                                    }
                                                }
                                            }
                                        }
                                    }

                , rb);
    }

    private void jumpToOwnerCertOk(IndustryEntity ib) {
        HouseJumper.jumpToCertOk(this, ib);
        finish();
    }

    private void jumpToTenantCert2(IndustryEntity ie) {
        if (commID == null) {
            ToastHelper.getInstance()._toast("请先选择小区");
        } else {
            if (ie != null) {
                if (mBundle == null) {
                    mBundle = new Bundle();
                }
                if (ie.getApartments() != null && ie.getApartments().size() > 0) {
                    mBundle.putSerializable("industry", ie);
                    mBundle.putString("commID", commID);
                    HouseJumper.jumpToTenantHouseList(this, mBundle);
                } else {
                    mBundle.putString("applicationID", ie.getApplicationID());
                    mBundle.putString("commID", commID);
                    HouseJumper.jumpToTenantCert2(this, mBundle);
                }
            }
        }
    }


    /*----------选择城市部分------------*/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        Bundle bundle = data.getExtras();
        if (bundle == null) {
            return;
        }
        LocationBean lb = (LocationBean) bundle.getSerializable(SelectHouseLocationActivity.INTENT_RESULT);
        setLocationInfo(lb);
    }

    /**
     * 选择位置完成后，将值设到TextView上
     *
     * @param lb 位置信息实体
     */
    private void setLocationInfo(LocationBean lb) {
        if (lb == null || currentType == null) {/*currentType可能是空的*/
            return;
        }
        if (SelectHouseLocationActivity.TYPE_CITY.equals(currentType)) {
            tvCity.setText(lb.getCity());
        } else if (SelectHouseLocationActivity.TYPE_COMM.equals(currentType)) {
            tvComm.setText(lb.getComm());
            commID = lb.getCommID();
        }
    }

    /**
     * @param type 选择位置的类型=城市、小区、楼栋、房号
     * @return 前一个值，请求需要；
     */
    private String hasSelectPreValue(String type) {
        String city = tvCity.getText().toString();
        if (type.equals(SelectHouseLocationActivity.TYPE_COMM) && !city.equals(PLEASE_SELECT) && !"".equals(city)) {
            return city;
        }
        return null;
    }

    private void resetSelected() {
        if (currentType == null) {
            return;
        }
        if (currentType.equals(SelectHouseLocationActivity.TYPE_CITY)) {
            tvComm.setText(PLEASE_SELECT);
            commID = "";
        }
    }

    /*----------验证码部分------------*/

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SmsHttpBiz.WHAT_SMS:
                    handleCode(msg, HouseCertActivity.this.getResources().getString(R.string.send_sms_fail), HouseCertActivity.this.getResources().getString(
                            R.string.send_sms_success));
                    break;
                case SmsHttpBiz.WHAT_VOICE_CODE:
                    handleCode(msg, HouseCertActivity.this.getResources().getString(R.string.send_voice_fail), HouseCertActivity.this.getResources().getString(
                            R.string.send_voice_success));
                    break;
                default:
                    break;
            }
        }

    };

    private void handleCode(Message msg, String okMsg, String failMsg) {
        closeDialog();
        boolean isOk2 = OrangeErrorHandler.getInstance().isSuccess(msg.obj, okMsg, failMsg);
        if (!isOk2) {
            stopTimer();
        }
    }

    @OnClick({R.id.tvGetCode, R.id.tvVoiceCode})
    public void onGetCode(View view) {
        String phone = tvTel.getText().toString();
        disableCode();
        if (LoginBiz.validatePhoneNum(phone, this)) {
            showDialog(this);
            switch (view.getId()) {
                case R.id.tvGetCode:
                    isSendSms = true;
                    requestSmsCode(phone);
                    break;
                case R.id.tvVoiceCode:
                    isSendSms = false;
                    requestVoiceCode(phone);
                    break;
            }
            startTimer("60");
        } else {
            enableCode();
        }
    }

    /** 请求短信验证码 */
    private void requestSmsCode(String phone) {
        SmsHttpBiz.getSmsCode(phone, mHandler, SmsHttpBiz.WHAT_SMS);
    }

    /** 请求语音验证码 */
    private void requestVoiceCode(String phone) {
        SmsHttpBiz.getVoiceCode(phone, mHandler);
    }

    private void disableCode() {
        etVerifyCode.setText("");
        tvGetCode.setEnabled(false);
        tvVoiceCode.setEnabled(false);
    }

    private void enableCode() {
        tvGetCode.setEnabled(true);
        tvVoiceCode.setEnabled(true);
        tvVoiceCode.setText(getResources().getString(
                R.string.voice_code));
        tvGetCode.setText(getResources().getString(R.string.send_again));
    }

    //初始化
    private void startTimer(String second) {
        if (countDownHandler == null) {
            countDownHandler = new CountDownHandler();
            countDownHandler.isOnlySecond(true);
            countDownHandler.isUseCustomCountDownInfo(true);
            countDownHandler.setOnCountDownTimerFinishedListener(new CountDownHandler.OnCountDownTimerFinishedListener() {
                @Override
                public void onFinish() {
                    enableCode();
                }

                @Override
                public void onCountDown(String currentSecond) {
                    String str = getResources().getString(R.string.count_down_info, currentSecond);
                    if (isSendSms) {
                        tvGetCode.setText(str);
                        etVerifyCode.setHint("请输入短信验证码");
                    } else {
                        tvVoiceCode.setText(str);
                        etVerifyCode.setHint("请输入语音验证码");
                    }
                }
            });
        }
        countDownHandler.startTimer(second);
    }

    private void stopTimer() {
        if (countDownHandler != null && isCountDown) {
            countDownHandler.stopTimer();
            isCountDown = false;
        }
    }

    /*----------选择角色------------*/

    // TODO: 2016/6/21 这个弹出框太丑了
    private void showPopWinChooseIdentity() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.popwin_house_identity, null);
        TextView tvItemFamily = (TextView) contentView.findViewById(R.id.tvItemFamily);
        TextView tvItemTenant = (TextView) contentView.findViewById(R.id.tvItemTenant);
        TextView tvItemOwner = (TextView) contentView.findViewById(R.id.tvItemOwner);
        tvItemFamily.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                identity = HouseBean.ROLE_TYPE_FAMILY_CODE;
                tvIdentity.setText("我是" + getResources().getString(R.string.family));
                if (pw != null) {
                    pw.dismiss();
                }
                type = "1";
            }
        });
        tvItemTenant.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                identity = HouseBean.ROLE_TYPE_TENANT_CODE;
                tvIdentity.setText("我是" + getResources().getString(R.string.tenant));
                if (pw != null) {
                    pw.dismiss();
                }
                type = "2";
            }
        });
        tvItemOwner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                identity = HouseBean.ROLE_TYPE_OWNER_CODE;
                tvIdentity.setText("我是" + getResources().getString(R.string.owner));
                if (pw != null) {
                    pw.dismiss();
                }
                type = "0";
            }
        });
        pw = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        pw.setOutsideTouchable(true);
        pw.setBackgroundDrawable(new BitmapDrawable());
        pw.showAsDropDown(tvIdentity, -50, 50);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }
}
